package top.codestudy.storageandroid10;

import androidx.appcompat.app.AppCompatActivity;
import androidx.documentfile.provider.DocumentFile;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.ParcelFileDescriptor;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.provider.OpenableColumns;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class SharedStorageActivity extends AppCompatActivity implements View.OnClickListener {
    private static final String TAG = "SharedStorageActivity";
    // Request code for creating a PDF document.
    private static final int CREATE_FILE = 1;
    // Request code for selecting a PDF document.
    private static final int PICK_FILE = 2;
    private static final int PICK_Directory = 3;

    private EditText mEtCreateFile;
    private Button mBtnCreateSharedFile;
    private Button mBtnOpenSharedFile;
    private Button mBtnOpenSharedDir;
    private Button mBtnOpenMediaFile;

    private TextView mTvShowLog;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_shared_storage);
        initView();


    }

    private void initView() {
        mEtCreateFile = findViewById(R.id.et_create_file);
        mBtnCreateSharedFile = findViewById(R.id.btn_create_shared_file);
        mBtnOpenSharedFile = findViewById(R.id.btn_open_shared_file);
        mBtnCreateSharedFile.setOnClickListener(this);
        mBtnOpenSharedFile.setOnClickListener(this);
        mBtnOpenSharedDir = findViewById(R.id.btn_open_shared_dir);
        mBtnOpenSharedDir.setOnClickListener(this);
        mBtnOpenMediaFile = findViewById(R.id.btn_open_media_file);
        mBtnOpenMediaFile.setOnClickListener(this);
        mTvShowLog = findViewById(R.id.tv_show_log);


    }

    //设置创建的文件名
    public String getEtCreateFileName(){
        return mEtCreateFile.getText().toString();
    }


    public static void goSharedStorageActivity(Context activity){
        Intent intent = new Intent(activity,SharedStorageActivity.class);
        activity.startActivity(intent);
    }

    //创建公共共享的文件
    private void createFile(Uri pickerInitialUri) {
        if (getEtCreateFileName() == null || "".equals(getEtCreateFileName())){
            showShort("createFile: file is null!");
            return;
        }
        Intent intent = new Intent(Intent.ACTION_CREATE_DOCUMENT);
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        intent.setType("application/text");
        intent.putExtra(Intent.EXTRA_TITLE, getEtCreateFileName()+".txt");

        // Optionally, specify a URI for the directory that should be opened in
        // the system file picker when your app creates the document.
        if (pickerInitialUri != null)
            intent.putExtra(DocumentsContract.EXTRA_INITIAL_URI, pickerInitialUri);

        startActivityForResult(intent, CREATE_FILE);
    }

    //打开公共共享的文件
    private void openFile(Uri pickerInitialUri) {
        Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        intent.setType("*/*");

        // Optionally, specify a URI for the file that should appear in the
        // system file picker when it loads.
        if (pickerInitialUri != null)
            intent.putExtra(DocumentsContract.EXTRA_INITIAL_URI, pickerInitialUri);

        startActivityForResult(intent, PICK_FILE);
    }

    public void openDirectory(Uri uriToLoad) {
        // Choose a directory using the system's file picker.
        Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE);

        // Provide read access to files and sub-directories in the user-selected
        // directory.
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

        // Optionally, specify a URI for the directory that should be opened in
        // the system file picker when it loads.
        if (uriToLoad != null)
            intent.putExtra(DocumentsContract.EXTRA_INITIAL_URI, uriToLoad);

        startActivityForResult(intent, PICK_Directory);
    }


    //像目标uri写入数据
    private void alterDocument(Uri uri) {
        try {
            ParcelFileDescriptor pfd = getContentResolver().
                    openFileDescriptor(uri, "w");
            FileOutputStream fileOutputStream =
                    new FileOutputStream(pfd.getFileDescriptor());
            fileOutputStream.write(("chencheng ==> Overwritten at " + System.currentTimeMillis() +
                    "\n").getBytes());
            // Let the document provider know you're done by closing the stream.
            fileOutputStream.close();
            pfd.close();
            Log.i(TAG, "alterDocument: 数据写入成功！！");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.btn_create_shared_file:
                //创建共享文件
                createFile(null);
                break;
            case R.id.btn_open_shared_file:
                //打开共享文件
                openFile(null);
                break;
            case R.id.btn_open_shared_dir:
                //打开共享目录
                openDirectory(null);
                break;
            case R.id.btn_open_media_file:
                accessMediaFile();
                break;
        }
    }

    private void accessMediaFile() {
        Cursor cursor = getApplicationContext().getContentResolver().query(
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                null,
                null,
                null,
                null
        );

        while (cursor.moveToNext()) {
            int columnIndex = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DISPLAY_NAME);
            Log.i(TAG, "accessMediaFile: file name ==> " + cursor.getString(columnIndex));

        }

    }

    public void showShort(String msg) {
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
        Log.d(TAG, "showShort: " + msg);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode,
                                 Intent resultData) {
        super.onActivityResult(requestCode, resultCode, resultData);
        if (resultCode == Activity.RESULT_OK){
            Uri uri = null;
            if (resultData != null) {
                uri = resultData.getData();
                Log.d(TAG, "onActivityResult: uri ==> " + uri.toString());
                switch (requestCode){
                    case CREATE_FILE:
                        break;
                    case PICK_FILE:
                        alterDocument(uri);
                        break;
                    case PICK_Directory:
                        showAllFile(uri);
                        break;
                }
            }

        }
    }

    private void showAllFile(Uri uri) {
        DocumentFile documentFile = DocumentFile.fromTreeUri(getApplication(), uri);
        Log.d(TAG, "showAllFile: is dir ==> " + documentFile.isDirectory());
        DocumentFile[] documentFiles = documentFile.listFiles();
        for(DocumentFile d: documentFiles){
            Log.d(TAG, "showAllFile: d ==> " + d.getName() + "; uri = " + d.getUri());
        }
    }
}